package com.atlin.project.utils;

import com.atlin.project.common.ErrorCode;
import com.atlin.project.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MailUtil {

    @Value("${spring.mail.username}")
    private String sender;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    TemplateEngine templateEngine;

    public static final String tempTemplateName = "regmail.html";


    //发送html内容的邮件,使用thymeleaf渲染页面
    public void sendHtmlMail(String from, String to, HashMap<String, String> content) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("数据异常告警信息");
        helper.setFrom(from);
        helper.setTo(to);

        helper.setSentDate(new Date());
        //生成邮件模板上的内容
        Context context = new Context();
        if (content != null && content.size() > 0) {
            for (String key : content.keySet()) {
                context.setVariable(key, content.get(key));
            }
        }
        String process = templateEngine.process(tempTemplateName, context);
        helper.setText(process, true);
        javaMailSender.send(mimeMessage);
    }

    /**
     * 发送HTML内容的邮件（使用Thymeleaf模板引擎）
     *
     * @param from         发件人
     * @param to           收件人（多个收件人可以用逗号分隔）
     * @param subject      邮件主题
     * @param templateName 模板文件名（不带.html后缀）
     * @param content      模板变量Map
     * @throws MessagingException 邮件发送异常
     */
    public void sendHtmlMail(String from, String to, String subject, String templateName, Map<String, Object> content) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

            // 设置基本信息
            helper.setSubject(subject);
            helper.setFrom(from);
            helper.setTo(to.split(",\\s*")); // 支持多个收件人
            helper.setSentDate(new Date());

            // 设置模板变量
            Context context = new Context();
            if (content != null) {
                context.setVariables(content);
            }

            // 渲染模板
            String emailContent = templateEngine.process(templateName, context);
            helper.setText(emailContent, true);

            // 发送邮件
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("发送HTML邮件失败，{}-{}-{}", from, to, content, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "邮件发送失败");
        }
    }

    public void sendHtmlMail(String to, String subject, String templateName, Map<String, Object> content) {
        sendHtmlMail(sender, to, subject, templateName, content);
    }

    public void sendCbMail(String to, Map<String, Object> content) {
        String subject = "可转债打新提醒";
        String templateName = "bondMail";
        sendHtmlMail(sender, to, subject, templateName, content);
    }
}